package com.xu.cloud.common.process.support;

import com.xu.cloud.common.pojo.http.req.BaseRequest;
import com.xu.cloud.common.process.AbsXuApiFactoryBean;
import com.xu.cloud.common.process.IProcessor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.target.SingletonTargetSource;

import java.lang.reflect.Method;

/**
 * 基于spring AopProxy, 创建增强业务执行接口代理方法的FactoryBean
 *
 * @author xuguan
 * @since 2025/1/23
 * @see org.aopalliance.intercept.MethodInterceptor
 * @see org.springframework.aop.framework.ProxyFactory
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class XuApiAopProxyFactoryBean<T> extends AbsXuApiFactoryBean<T> implements MethodInterceptor {

    @Override
    protected T getProxy() {
        return (T) getProxyFactory().getProxy();
    }

    protected ProxyFactory getProxyFactory() {
        final ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.addAdvice(this);
        final Class<T> target = getTarget();
        if (target.isInterface()) {
            proxyFactory.addInterface(target);
        } else {
            proxyFactory.setTargetClass(target);
            proxyFactory.setProxyTargetClass(true);
        }
        proxyFactory.setTargetSource(new SingletonTargetSource(target));
        return proxyFactory;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        final Method method = invocation.getMethod();
        final Object[] args = invocation.getArguments();
        final Object target = invocation.getThis();
        if (args != null && args.length == 1 && BaseRequest.class.isAssignableFrom(args[0].getClass())) {
            final IProcessor processor = getProcessSelector().select(method);
            return processor.process((BaseRequest) args[0]);
        }
        return method.invoke(target, args);
    }
}
